package com.jalarbee.web.jsf.converter;

import com.jalarbee.stock.product.business.Quantity;
import com.jalarbee.stock.product.util.QuantityUtil;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

/**
 *
 * @author devel
 */

public class QuantityConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String string) {
        try {
            return QuantityUtil.parse(string);
        } catch(Exception exception) {
            FacesMessage message = new FacesMessage();
            message.setDetail(exception.getMessage());
            message.setSummary(exception.getMessage());
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            context.addMessage(component.getId(), message);
            throw new ConverterException(message);
        }
        
    }

    @Override
    public String getAsString(FacesContext fc, UIComponent uic, Object o) {
        return ((Quantity)o).toString();
    }

}
